// STL
#include <cmath>                    // std::exp(), ::pow()
#include <stdexcept>                // std::runtime_error()

// stats++
#include "statsxx/distribution.hpp" // distribution::P_KS


//
// DESC: Calculate the complementary cumulative distribution function of the Kolmogorov--Smirnov distribution.
//
// -----
//
// NOTE: See "Numerical Recipes, 3rd Ed." Section 6.14.12.
//
inline double distribution::Q_KS(
                                 const double z
                                 )
{
    if( z < 0. )
    {
        throw std::runtime_error("bad z in distribution::Q_KS()");
    }

    if( z == 0. )
    {
        return 1.;
    }

    if( z < 1.18 )
    {
        return (1. - distribution::P_KS(z));
    }

    double x = std::exp(-2*z*z);

    return ( 2*(x - std::pow(x,4) + std::pow(x,9)) );
}
